package com.seeyon.apps.kk.manager;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.seeyon.apps.kk.manager.datasync.AbstractDataSyncManager;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.i18n.ResourceUtil;
import com.seeyon.ctp.organization.bo.OrganizationMessage;
import com.seeyon.ctp.organization.bo.OrganizationMessage.OrgMessage;
import com.seeyon.ctp.organization.bo.V3xOrgDepartment;
import com.seeyon.ctp.organization.bo.V3xOrgEntity;
import com.seeyon.ctp.organization.bo.V3xOrgLevel;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.bo.V3xOrgPost;
import com.seeyon.ctp.organization.bo.V3xOrgPrincipal;
import com.seeyon.ctp.organization.bo.V3xOrgRole;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.organization.manager.OrgManagerDirect;
import com.seeyon.v3x.services.form.FormFactory;
import com.seeyon.v3x.services.form.FormUtils;
import com.seeyon.v3x.services.form.bean.FormExport;

import jersey.repackaged.com.google.common.collect.Maps;

public class OrgSyncManager extends AbstractDataSyncManager {
	private static final Log log = LogFactory.getLog(OrgSyncManager.class);

	private OrganizationMessage organizationMessage;

	private OrgManager orgManager;

	private OrgManagerDirect orgManagerDirect;

	protected Map<String, String> sqlMap = new HashMap<String, String>();

	private static JdbcTemplate jdbc = (JdbcTemplate) AppContext.getBean("ghrjdbcTemplate");

	public Map<String, String> getSqlMap() {
		return sqlMap;
	}

	public void setSqlMap(Map<String, String> sqlMap) {
		this.sqlMap = sqlMap;
	}

	private Long accountId;// 当前单位id

	private KKADSyncManager kkadSyncManager;

	public KKADSyncManager getKkadSyncManager() {
		return kkadSyncManager;
	}

	public void setKkadSyncManager(KKADSyncManager kkadSyncManager) {
		this.kkadSyncManager = kkadSyncManager;
	}

	private FreemarkFlowManager freemarkFlowManager;

	public FreemarkFlowManager getFreemarkFlowManager() {
		return freemarkFlowManager;
	}

	public void setFreemarkFlowManager(FreemarkFlowManager freemarkFlowManager) {
		this.freemarkFlowManager = freemarkFlowManager;
	}

	@Override
	public boolean beforeGrabData() {
		// TODO Auto-generated method stub
		try {
			kkSaveSync();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean grabData() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean addData() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean updateData() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean deleteData() {
		// TODO Auto-generated method stub
		return false;
	}

	/**
	 * 
	 * 组织架构同步总入口
	 * 
	 * @throws Exception
	 *             void
	 */
	public Map<String, String> kkSaveSync() throws Exception {
		List<Map<String, Object>> sortL = this.ibatisQueryDao.queryForList("getCompanyId_select_lockkk", null);
		Map<String, Object> sortM = sortL.get(0);
		this.accountId = (long) MapUtils.getLong(sortM, "id");
		Map<String, String> rMap = new HashMap();
		if (!this.apiDataDealt(rMap))
			return rMap;
		if (!this.departmentAdd(rMap))
			return rMap;
		if (!this.departmentUpdate(rMap))
			return rMap;
		if (!this.postAdd(rMap))
			return rMap;
		if (!this.postUpdate(rMap))
			return rMap;
		if (!this.levelAdd(rMap))
			return rMap;
		if (!this.levelUpdate(rMap))
			return rMap;
		if (!this.memberAdd(rMap))
			return rMap;
		if (!this.memberUpdate(rMap))
			return rMap;
		if (!this.relationshipUpdate(rMap))
			return rMap;
		if (!this.addEstab(rMap))
			return rMap;
		rMap = this.kkadSyncManager.adSync();
		return rMap;
	}

	/**
	 * 同步数据初始化
	 * 
	 * @param rMap
	 * @return
	 */
	@SuppressWarnings("deprecation")
	private boolean apiDataDealt(Map<String, String> rMap) {
		try {
			log.info("==========OrgSyncManager apiDataDealt start");
			// 获取基础信息表插入到基础临时表内
			List<Map<String, Object>> result = this.jdbc.queryForList(this.sqlMap.get("basicinfo_select_lockkk"));
			if (CollectionUtils.isEmpty(result)) {
				rMap.put("code", "1001");
				rMap.put("result", "apiDataDealt fail;DepList is empty ");
				log.error("OrgSyncManager apiDataDealt error! DepList is empty====");
				return false;
			}
			// 1:删除基础临时表
			this.ibatisQueryDao.getSqlMapClientTemplate().delete("basicinfo_delete_lockkk", null);
			for (Map<String, Object> mapBean : result) {
				mapBean.put("FIELD", MapUtils.getString(mapBean, "FIELD").replace(" ", ""));
				mapBean.put("CODE", MapUtils.getString(mapBean, "CODE").replace(" ", ""));
				mapBean.put("EFF_STATUS", MapUtils.getString(mapBean, "EFF_STATUS").replace(" ", ""));
				mapBean.put("LANG_CD", MapUtils.getString(mapBean, "LANG_CD").replace(" ", ""));
				mapBean.put("CODE_NM", MapUtils.getString(mapBean, "CODE_NM").replace(" ", ""));
				/**
				 * ADD_DTTM = '2001-01-01 01:01:01.0' 因使用oracle数据库，新增时
				 * to_date格式化错误，需提前格式化 下同
				 */
				String addDttm = MapUtils.getString(mapBean, "ADD_DTTM");
				String updDttm = MapUtils.getString(mapBean, "UPD_DTTM");

				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Date dataAdd = format.parse(addDttm);
				Date dataUpd = format.parse(updDttm);
				mapBean.put("ADD_DTTM", format.format(dataAdd));
				mapBean.put("UPD_DTTM", format.format(dataUpd));
				this.ibatisQueryDao.getSqlMapClientTemplate().insert("basicinfo_insert_lockkk", mapBean);
			}
			// 获取部门信息插入到部门临时表内
			result = this.jdbc.queryForList(this.sqlMap.get("dept_select_lockkk"));
			if (CollectionUtils.isEmpty(result)) {
				rMap.put("code", "1001");
				rMap.put("result", "apiDataDealt fail;DepList is empty ");
				log.error("OrgSyncManager apiDataDealt error! DepList is empty====");
				return false;
			}
			this.ibatisQueryDao.getSqlMapClientTemplate().delete("dept_delete_lockkk");
			for (Map<String, Object> mapBean : result) {
				mapBean.put("COMPANY", MapUtils.getString(mapBean, "COMPANY").replace(" ", ""));
				mapBean.put("DEPT", MapUtils.getString(mapBean, "DEPT").replace(" ", ""));
				mapBean.put("PARENT_DEPT",
						MapUtils.getString(mapBean, "PARENT_DEPT") == null ? MapUtils.getString(mapBean, "PARENT_DEPT")
								: MapUtils.getString(mapBean, "PARENT_DEPT").replace(" ", ""));
				mapBean.put("MNG_EMPNO",
						MapUtils.getString(mapBean, "MNG_EMPNO") == null ? MapUtils.getString(mapBean, "MNG_EMPNO")
								: MapUtils.getString(mapBean, "MNG_EMPNO").replace(" ", ""));
				mapBean.put("NAME1", MapUtils.getString(mapBean, "NAME1") == null ? MapUtils.getString(mapBean, "NAME1")
						: MapUtils.getString(mapBean, "NAME1").replace(" ", ""));

				String addDttm = MapUtils.getString(mapBean, "ADD_DTTM");
				String updDttm = MapUtils.getString(mapBean, "UPD_DTTM");

				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Date dataAdd = format.parse(addDttm);
				Date dataUpd = format.parse(updDttm);
				mapBean.put("ADD_DTTM", format.format(dataAdd));
				mapBean.put("UPD_DTTM", format.format(dataUpd));
				this.ibatisQueryDao.getSqlMapClientTemplate().insert("dept_insert_lockkk", mapBean);
			}

			// 获取职工信息插入到职工临时表内
			result = this.jdbc.queryForList(this.sqlMap.get("staff_select_lockkk"));
			if (CollectionUtils.isEmpty(result)) {
				rMap.put("code", "1001");
				rMap.put("result", "apiDataDealt fail;postList is empty ");
				log.error("OrgSyncManager apiDataDealt error! postList is empty====");
				return false;
			}
			// 1:删除职工临时表
			this.ibatisQueryDao.getSqlMapClientTemplate().delete("staff_delete_lockkk", null);
			for (Map<String, Object> mapBean : result) {
				mapBean.put("EMPNO", MapUtils.getString(mapBean, "EMPNO") == null ? MapUtils.getString(mapBean, "EMPNO")
						: MapUtils.getString(mapBean, "EMPNO").replace(" ", ""));
				mapBean.put("EMPID", MapUtils.getString(mapBean, "EMPID") == null ? MapUtils.getString(mapBean, "EMPID")
						: MapUtils.getString(mapBean, "EMPID").replace(" ", ""));
				mapBean.put("COMPANY",
						MapUtils.getString(mapBean, "COMPANY") == null ? MapUtils.getString(mapBean, "COMPANY")
								: MapUtils.getString(mapBean, "COMPANY").replace(" ", ""));
				mapBean.put("DEPT", MapUtils.getString(mapBean, "DEPT") == null ? MapUtils.getString(mapBean, "DEPT")
						: MapUtils.getString(mapBean, "DEPT").replace(" ", ""));
				mapBean.put("JOB_TITLE",
						MapUtils.getString(mapBean, "JOB_TITLE") == null ? MapUtils.getString(mapBean, "JOB_TITLE")
								: MapUtils.getString(mapBean, "JOB_TITLE").replace(" ", ""));
				mapBean.put("JOB_POSITION",
						MapUtils.getString(mapBean, "JOB_POSITION") == null
								? MapUtils.getString(mapBean, "JOB_POSITION")
								: MapUtils.getString(mapBean, "JOB_POSITION").replace(" ", ""));

				String addDttm = MapUtils.getString(mapBean, "ADD_DTTM");
				String updDttm = MapUtils.getString(mapBean, "UPD_DTTM");

				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Date dataAdd = format.parse(addDttm);
				Date dataUpd = format.parse(updDttm);
				mapBean.put("ADD_DTTM", format.format(dataAdd));
				mapBean.put("UPD_DTTM", format.format(dataUpd));
				this.ibatisQueryDao.getSqlMapClientTemplate().insert("staff_insert_lockkk", mapBean);
			}

			// 获取个人信息插入到个人临时表内
			result = this.jdbc.queryForList(this.sqlMap.get("person_select_lockkk"));
			if (CollectionUtils.isEmpty(result)) {
				rMap.put("code", "1001");
				rMap.put("result", "apiDataDealt fail;userList is empty ");
				log.error("OrgSyncManager apiDataDealt error! userList is empty====");
				return false;
			}
			// 1:删除
			this.ibatisQueryDao.getSqlMapClientTemplate().delete("person_delete_lockkk", null);
			for (Map<String, Object> mapBean : result) {
				mapBean.put("COMPANY",
						MapUtils.getString(mapBean, "COMPANY") == null ? MapUtils.getString(mapBean, "COMPANY")
								: MapUtils.getString(mapBean, "COMPANY").replace(" ", ""));
				mapBean.put("EMPID", MapUtils.getString(mapBean, "EMPID") == null ? MapUtils.getString(mapBean, "EMPID")
						: MapUtils.getString(mapBean, "EMPID").replace(" ", ""));
				mapBean.put("JOB_TITLE",
						MapUtils.getString(mapBean, "JOB_TITLE") == null ? MapUtils.getString(mapBean, "JOB_TITLE")
								: MapUtils.getString(mapBean, "JOB_TITLE").replace(" ", ""));
				mapBean.put("JOB_POSITION",
						MapUtils.getString(mapBean, "JOB_POSITION") == null
								? MapUtils.getString(mapBean, "JOB_POSITION")
								: MapUtils.getString(mapBean, "JOB_POSITION").replace(" ", ""));
				mapBean.put("PHONE", MapUtils.getString(mapBean, "PHONE") == null ? MapUtils.getString(mapBean, "PHONE")
						: MapUtils.getString(mapBean, "PHONE").replace(" ", ""));

				String addDttm = MapUtils.getString(mapBean, "ADD_DTTM");
				String updDttm = MapUtils.getString(mapBean, "UPD_DTTM");

				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Date dataAdd = format.parse(addDttm);
				Date dataUpd = format.parse(updDttm);
				mapBean.put("ADD_DTTM", format.format(dataAdd));
				mapBean.put("UPD_DTTM", format.format(dataUpd));
				String phone = MapUtils.getString(mapBean, "PHONE_CELL") == null
						? MapUtils.getString(mapBean, "PHONE_CELL")
						: MapUtils.getString(mapBean, "PHONE_CELL").replaceAll("-", "").replaceAll(" ", "");
				mapBean.put("PHONE_CELL", phone);
				this.ibatisQueryDao.getSqlMapClientTemplate().insert("person_insert_lockkk", mapBean);
			}

			rMap.put("code", "1000");
			rMap.put("result", "apiDataDealt succ");
			log.info("==========OrgSyncManager apiDataDealt end");
		} catch (Exception e) {
			rMap.put("code", "1001");
			rMap.put("result", "apiDataDealt fail");
			log.error("OrgSyncManager apiDataDealt error", e);
			e.printStackTrace();
		} finally {
			return StringUtils.equals("1000", rMap.get("code")) ? true : false;
		}
	}

	private void toLower(Map<String, String> mapBean) {
		if (null == mapBean)
			return;
		Map<String, String> newMap = new HashMap();
		newMap.putAll(mapBean);
		mapBean.clear();
		for (String key : newMap.keySet()) {
			mapBean.put(StringUtils.lowerCase(key), newMap.get(key));
		}
	}

	private String toString(String result) {
		try {
			JSONObject json = JSON.parseObject(result);
			return json.getString("Result");
		} catch (Exception e) {
			log.error("OrgSyncManager  toString error !result=" + result, e);
			e.printStackTrace();
			return "";
		}

	}

	private List<Map<String, String>> toList(String result, String type) {
		List<Map<String, String>> rList = null;

		try {
			JSONObject json = JSON.parseObject(result);
			if (!StringUtils.equals("0", json.getString("MsgId"))) {
				log.error("OrgSyncManager  toList error ! MsgId != 0 result=" + result + " type=" + type);
				return rList;
			}
			json = JSON.parseObject(json.getString("Result"));
			json = JSON.parseObject(json.getString(type));
			rList = JSON.parseObject(json.getString("Row"), new TypeReference<List<Map<String, String>>>() {
			});
		} catch (Exception e) {
			log.error("OrgSyncManager  toList error !result=" + result + " type=" + type, e);
			e.printStackTrace();
		} finally {
			return rList;
		}
	}

	/**
	 * 给hrdep 重新排列级次
	 * 
	 * @param hrDepList
	 */
	private List<Map<String, Object>> sortDepList(List<Map<String, Object>> hrDepList) {
		if (CollectionUtils.isEmpty(hrDepList))
			return hrDepList;

		Map<String, Integer> gradeMap = Maps.newHashMap();
		for (Map<String, Object> dep : hrDepList) {
			if (StringUtils.equals("", MapUtils.getString(dep, "supcode"))) {
				gradeMap.put(MapUtils.getString(dep, "dcode"), 0);
				dep.put("dlevel", 0);
				continue;
			}

			if (null != gradeMap.get(MapUtils.getString(dep, "supcode"))) {// 如果当前的父部门code
																			// 在
																			// gradeMap
																			// 存在
				int dlevel = MapUtils.getInteger(gradeMap, MapUtils.getString(dep, "supcode")).intValue() + 1;
				gradeMap.put(MapUtils.getString(dep, "dcode"), dlevel);
				dep.put("dlevel", dlevel);
				continue;
			}
			// 如果上级没有在gradeMap 中 ，则递归去找上级
			dgSortDepList(hrDepList, dep, gradeMap);
		}
		return hrDepList;
	}

	/**
	 * 递归hrdep
	 * 
	 * @param hrDepList
	 * @param gradeMap
	 */
	private void dgSortDepList(List<Map<String, Object>> hrDepList, Map<String, Object> curdep,
			Map<String, Integer> gradeMap) {
		if (StringUtils.equals("", MapUtils.getString(curdep, "supcode"))) {
			gradeMap.put(MapUtils.getString(curdep, "dcode"), 0);
			curdep.put("dlevel", 0);
			return;
		}

		if (null != gradeMap.get(MapUtils.getString(curdep, "supcode"))) {// 如果当前的父部门code
																			// 在
																			// gradeMap
																			// 存在
			int dlevel = MapUtils.getInteger(gradeMap, MapUtils.getString(curdep, "supcode")).intValue() + 1;
			gradeMap.put(MapUtils.getString(curdep, "dcode"), dlevel);
			curdep.put("dlevel", dlevel);
			return;
		}
		int dlevel = 0;
		// 递归轮询当前部门的父部门code，把所有父部门code 存入gradeMap后且设置好父部门的dlevel，
		// 再将当前部门code存入gradeMap并设置自己的dlevel
		for (Map<String, Object> dep : hrDepList) {
			if (StringUtils.equals(MapUtils.getString(curdep, "supcode"), MapUtils.getString(dep, "dcode"))) {
				if (null == gradeMap.get(MapUtils.getString(curdep, "supcode"))) {// 如果当前的父部门code
																					// 在
																					// gradeMap
																					// 不存在，就去递归找上级，直到找到为止
					dgSortDepList(hrDepList, dep, gradeMap);
				}
				if (null != gradeMap.get(MapUtils.getString(curdep, "supcode"))) {
					dlevel = (null == MapUtils.getInteger(gradeMap, MapUtils.getString(curdep, "supcode")) ? 0
							: (MapUtils.getInteger(gradeMap, MapUtils.getString(curdep, "supcode")).intValue() + 1));
					gradeMap.put(MapUtils.getString(curdep, "dcode"), dlevel);
					curdep.put("dlevel", dlevel);
				}
			}
		}
	}

	private String replacePageSize(String sql, int startSort, int endSort) {
		sql = sql.replace("#startSort#", startSort + "");
		sql = sql.replace("#endSort#", endSort + "");
		return sql;
	}

	private String checkUcode(List<Map<String, Object>> userList, String uid) {
		String uCode = "";
		for (Map<String, Object> map : userList) {
			if (StringUtils.equals(uid, MapUtils.getString(map, "id"))) {
				uCode = MapUtils.getString(map, "uCode");
				break;
			}
		}
		return uCode;
	}

	/**
	 * 更新人员关系 void
	 * 
	 * @param rMap
	 * @throws BusinessException
	 */
	private boolean relationshipUpdate(Map<String, String> rMap) {
		try {
			log.info("==========OrgSyncManager relationshipUpdate start");
			// 主管

			List<Map<String, Object>> managerlist = this.ibatisQueryDao.queryForList("deptRelation_select_lockkk",
					null);
			this.refreshManager("DepManager", managerlist);
			rMap.put("code", "1000");
			rMap.put("result", "relationshipUpdate succ");
			log.info("==========OrgSyncManager relationshipUpdate end");

		} catch (Exception e) {
			rMap.put("code", "1001");
			rMap.put("result", "relationshipUpdate fail");
			log.error("OrgSyncManager relationshipUpdate error", e);
			e.printStackTrace();
		} finally {
			return StringUtils.equals("1000", rMap.get("code")) ? true : false;
		}
	}

	/**
	 * 刷新部门主管人员（分管人员）
	 * 
	 * @param depManagerType
	 *            人员类型: DepManager 主管、DepLeader 分管、DepAdmin 部门管理员
	 * @param omList
	 *            需要更新的部门 人员 列表 每行记录 必须包含 UID（部门ID）、ID(人员ID)
	 * @throws com.seeyon.ctp.common.exceptions.BusinessException
	 */
	private void refreshManager(String depManagerType, List<Map<String, Object>> list) throws BusinessException {
		// 获取当前单位下的某种角色 DepManager 部门主管 DepLeader 部门分管领导
		V3xOrgRole role = orgManager.getRoleByName(depManagerType, this.accountId);
		Map<Long, V3xOrgDepartment> map = new HashMap<Long, V3xOrgDepartment>();
		for (Map<String, Object> mv : list) {
			Long did = MapUtils.getLong(mv, "did");
			Long mid = MapUtils.getLong(mv, "mid");
			V3xOrgDepartment vm = map.get(did);
			if (vm == null) {
				// 部门主管需要做调整，先清空当前部门的所有主管人员
				vm = this.orgManager.getDepartmentById(did);
				// 获取一个部门下 某个角色的人员并删除
				List<V3xOrgMember> memberlist = this.orgManager.getMembersByRole(vm.getId(), role.getId());
				if (!memberlist.isEmpty()) {
					this.orgManagerDirect.deleteRole2Entity(role.getId(), vm.getId(), memberlist);
				}
			}
			// 追加一个主管 到当前的部门
			V3xOrgMember v3xOrgMember = this.orgManager.getMemberById(mid);
			this.orgManagerDirect.addRole2Entity(role.getId(), vm.getOrgAccountId(), v3xOrgMember, vm);
			// 将部门加入map供后续使用
			map.put(did, vm);
		}
	}

	/**
	 * 
	 * 更新人员 void
	 * 
	 * @param rMap
	 */
	private boolean memberUpdate(Map<String, String> rMap) {
		try {
			log.info("==========OrgSyncManager memberUpdate start");
			List<Map<String, Object>> vl = this.ibatisQueryDao.queryForList("memberUpdate_select_lockkk", null);
			List<V3xOrgMember> list = new ArrayList<V3xOrgMember>();
			for (Map<String, Object> vm : vl) {
				V3xOrgMember member = this.orgManager.getMemberById(MapUtils.getLong(vm, "memberId"));
				member.setName(MapUtils.getString(vm, "name"));
				member.setOrgDepartmentId(StringUtils.isNotBlank(MapUtils.getString(vm, "deptid"))
						? Long.valueOf(MapUtils.getString(vm, "deptid")) : -1L);
				member.setOrgPostId(StringUtils.isNotBlank(MapUtils.getString(vm, "postid"))
						? Long.valueOf(MapUtils.getString(vm, "postid")) : -1L);
				member.setOrgLevelId(StringUtils.isNotBlank(MapUtils.getString(vm, "levelid"))
						? Long.valueOf(MapUtils.getString(vm, "levelid")) : -1L);
				member.setEnabled(MapUtils.getString(vm, "is_status").equals("1"));// status=1表示正常用户，0表示已禁用
				member.setState(MapUtils.getString(vm, "is_status").equals("1") ? 1 : 2);
				member.setProperty("telnumber", MapUtils.getString(vm, "telephone")); // 电话号码telephone
				member.setProperty("officenumber", MapUtils.getString(vm, "phone")); // 手机号phone
				member.setProperty("emailaddress", MapUtils.getString(vm, "email"));
				Map<String, Object> group = new HashMap<String, Object>();
				group.put("member_id", member.getId());
				group.put("company", MapUtils.getString(vm, "company"));
				this.ibatisQueryDao.getSqlMapClientTemplate().insert("group_update_lockkk", group);

				if (StringUtils.isBlank(member.getLoginName()) && "1".equals(MapUtils.getString(vm, "is_status"))) {
					// login 验证 getLoginName_select_lockkk
					String loginName = MapUtils.getString(vm, "login");
					Map<String, Object> query = new HashMap<String, Object>();
					query.put("name", loginName);
					List<Map<String, Object>> loginList = this.ibatisQueryDao.queryForList("getLoginName_select_lockkk",
							query);
					// 根据GHR邮箱截取loginName 存在相同追加1，2，3
					if (!loginList.isEmpty()) {
						for (Map<String, Object> v : loginList) {
							if (StringUtils.equals(MapUtils.getString(v, "login_name"), loginName)) {
								loginName = loginName + loginList.size();
								break;
							}
						}
					}
					V3xOrgPrincipal p = new V3xOrgPrincipal(member.getId(), loginName, "lock123456");
					member.setV3xOrgPrincipal(p);
					log.info("updateMember is add LoginName:" + loginName + ";name" + member.getName());
				}
				organizationMessage = this.orgManagerDirect.updateMember(member);
			}

			rMap.put("code", "1000");
			rMap.put("result", "memberUpdate succ");
			log.info("==========OrgSyncManager memberUpdate end");
		} catch (Exception e) {
			rMap.put("code", "1001");
			rMap.put("result", "memberUpdate fail");
			log.info("OrgSyncManager memberUpdate error", e);
			e.printStackTrace();
		} finally {
			return StringUtils.equals("1000", rMap.get("code")) ? true : false;
		}
	}

	/**
	 * 
	 * 新建人员 void
	 * 
	 * @param rMap
	 * @throws BusinessException
	 */
	private boolean memberAdd(Map<String, String> rMap) throws BusinessException {
		try {
			log.info("==========OrgSyncManager memberAdd start");
			List<Map<String, Object>> vl = this.ibatisQueryDao.queryForList("memberAdd_select_lockkk", null);

			// 查询人员最大排序号
			List<Map<String, Object>> sortL = this.ibatisQueryDao.queryForList("getMemberMaxSort_select_lolkk", null);
			Map<String, Object> sortM = sortL.get(0);
			int num = MapUtils.getInteger(sortM, "num").intValue();

			List<V3xOrgMember> list = new ArrayList<V3xOrgMember>();
			for (Map<String, Object> vm : vl) {
				num = num + 1;
				V3xOrgMember member = new V3xOrgMember();
				member.setIdIfNew();
				member.setOrgAccountId(this.accountId);
				member.setCode(MapUtils.getString(vm, "empno"));
				member.setName(MapUtils.getString(vm, "name"));
				member.setOrgDepartmentId(StringUtils.isNotBlank(MapUtils.getString(vm, "deptid"))
						? Long.valueOf(MapUtils.getString(vm, "deptid")) : -1L);
				member.setOrgPostId(StringUtils.isNotBlank(MapUtils.getString(vm, "postid"))
						? Long.valueOf(MapUtils.getString(vm, "postid")) : -1L);
				member.setOrgLevelId(MapUtils.getLong(vm, "levelid"));
				member.setSortId((long) num);
				member.setEnabled(true);

				member.setType(MapUtils.getInteger(vm, "type"));// 人员类型
				member.setProperty("telnumber", MapUtils.getString(vm, "telephone")); // 电话号码telephone
				member.setProperty("officenumber", MapUtils.getString(vm, "phone")); // 手机号phone
				member.setProperty("emailaddress", MapUtils.getString(vm, "email")); // customer_field
				/*
				 * member.setProperty("customer_field", MapUtils.getString(vm,
				 * ""));
				 */
				// login 验证 getLoginName_select_lockkk
				String loginName = MapUtils.getString(vm, "login");
				Map<String, Object> query = new HashMap<String, Object>();
				query.put("name", loginName);
				List<Map<String, Object>> loginList = this.ibatisQueryDao.queryForList("getLoginName_select_lockkk",
						query);
				// 根据GHR邮箱截取loginName 存在相同追加1，2，3
				if (!loginList.isEmpty()) {
					for (Map<String, Object> v : loginList) {
						if (StringUtils.equals(MapUtils.getString(v, "login_name"), loginName)) {
							loginName = loginName + loginList.size();
							break;
						}
					}
				}
				V3xOrgPrincipal p = new V3xOrgPrincipal(member.getId(), loginName, "lock123456");
				member.setV3xOrgPrincipal(p);
				Map<String, Object> group = new HashMap<String, Object>();
				group.put("member_id", member.getId());
				group.put("country", MapUtils.getString(vm, "country"));
				group.put("company", MapUtils.getString(vm, "company"));
				this.ibatisQueryDao.getSqlMapClientTemplate().insert("group_insert_lockkk", group);
				organizationMessage = this.orgManagerDirect.addMember(member);
				// this.parseOrganization(organizationMessage);
				list.add(member);
			}
			rMap.put("code", "1000");
			rMap.put("result", "memberAdd succ");
			log.info("==========OrgSyncManager memberAdd end");
		} catch (Exception e) {
			rMap.put("code", "1001");
			rMap.put("result", "memberAdd fail");
			log.error("OrgSyncManager memberAdd error", e);
			e.printStackTrace();
		} finally {
			return StringUtils.equals("1000", rMap.get("code")) ? true : false;
		}
	}

	/**
	 * 
	 * 更新职务 void
	 */
	private boolean levelUpdate(Map<String, String> rMap) {
		// TODO Auto-generated method stub
		log.info("==========OrgSyncManager levelUpdate start");
		List<Map<String, Object>> vl = this.ibatisQueryDao.queryForList("levelUpdate_select_lockkk", null);

		try {
			List<V3xOrgLevel> postList = new ArrayList<V3xOrgLevel>();
			for (Map<String, Object> vm : vl) {
				V3xOrgLevel level = this.orgManager.getLevelById(MapUtils.getLong(vm, "id"));
				Map<String, Object> query = new HashMap<String, Object>();
				query.put("NAME", MapUtils.getString(vm, "code_nm"));
				List<Map<String, Object>> nameList = this.ibatisQueryDao.queryForList("getLevelName_select_lockkk",
						query);
				if (!nameList.isEmpty()) {
					int indexFlag = 0;
					for (Map<String, Object> v : nameList) {
						if (StringUtils.equals(MapUtils.getString(v, "code"), level.getCode())) {
							indexFlag++;
							level.setName(MapUtils.getString(vm, "code_nm") + indexFlag);
						}
					}
				} else {
					level.setName(MapUtils.getString(vm, "code_nm"));
				}
				level.setLevelId(MapUtils.getInteger(vm, "sort"));// 根据code//
																	// 获取排位序号、typeid
				level.setSortId(null == MapUtils.getLong(vm, "sort") ? 1l : MapUtils.getLong(vm, "sort"));// 排序号
				level.setEnabled(MapUtils.getString(vm, "is_status").equals("1"));
				organizationMessage = this.orgManagerDirect.updateLevel(level);
				postList.add(level);
			}
			rMap.put("code", "1000");
			rMap.put("result", "levelAdd succ");
			log.info("==========OrgSyncManager levelUpdate end");
		} catch (Exception e) {
			rMap.put("code", "1001");
			rMap.put("result", "levelUpdate fail");
			log.error("OrgSyncManager levelUpdate error", e);
			e.printStackTrace();
		} finally {
			return StringUtils.equals("1000", rMap.get("code")) ? true : false;
		}

	}

	/**
	 * 
	 * 新建职务 void
	 */
	private boolean levelAdd(Map<String, String> rMap) {
		// TODO Auto-generated method stub
		log.info("==========OrgSyncManager levelAdd start");
		List<Map<String, Object>> vl = this.ibatisQueryDao.queryForList("levelAdd_select_lockkk", null);
		List<Map<String, Object>> sortL = this.ibatisQueryDao.queryForList("getLevelMaxSort_select_lockkk", null);
		Map<String, Object> sortM = sortL.get(0);
		int index = MapUtils.getInteger(sortM, "num").intValue();
		try {
			List<V3xOrgLevel> postList = new ArrayList<V3xOrgLevel>();
			for (Map<String, Object> vm : vl) {
				index++;
				V3xOrgLevel v3xOrgLevel = new V3xOrgLevel();
				v3xOrgLevel.setIdIfNew();
				v3xOrgLevel.setCode(MapUtils.getString(vm, "code"));
				v3xOrgLevel.setLevelId(MapUtils.getInteger(vm, "code"));
				// v3xOrgLevel.setName(MapUtils.getString(vm, "code_nm"));
				Map<String, Object> query = new HashMap<String, Object>();
				query.put("NAME", MapUtils.getString(vm, "code_nm"));
				List<Map<String, Object>> nameList = this.ibatisQueryDao.queryForList("getLevelName_select_lockkk",
						query);
				if (!nameList.isEmpty()) {
					for (Map<String, Object> v : nameList) {
						if (StringUtils.equals(MapUtils.getString(v, "name"), MapUtils.getString(vm, "code_nm"))) {
							v3xOrgLevel.setName(MapUtils.getString(vm, "code_nm") + nameList.size());
							break;
						} else {
							v3xOrgLevel.setName(MapUtils.getString(vm, "code_nm"));
						}
					}
				} else {
					v3xOrgLevel.setName(MapUtils.getString(vm, "code_nm"));
				}
				v3xOrgLevel.setSortId((long) index);// 排序号
				v3xOrgLevel.setOrgAccountId(this.accountId);
				organizationMessage = this.orgManagerDirect.addLevel(v3xOrgLevel);
				postList.add(v3xOrgLevel);
			}
			rMap.put("code", "1000");
			rMap.put("result", "levelAdd succ");
			log.info("==========OrgSyncManager levelAdd end");
		} catch (Exception e) {
			rMap.put("code", "1001");
			rMap.put("result", "levelAdd fail");
			log.error("OrgSyncManager levelAdd error", e);
			e.printStackTrace();
		} finally {
			return StringUtils.equals("1000", rMap.get("code")) ? true : false;
		}
	}

	/**
	 * 
	 * 更新岗位 void
	 */
	private boolean postUpdate(Map<String, String> rMap) {
		log.info("==========OrgSyncManager postUpdate start");
		List<Map<String, Object>> vl = this.ibatisQueryDao.queryForList("postUpdate_select_lockkk", null);

		try {
			List<V3xOrgPost> postList = new ArrayList<V3xOrgPost>();
			for (Map<String, Object> vm : vl) {
				V3xOrgPost post = this.orgManager.getPostById(MapUtils.getLong(vm, "id"));
				Map<String, Object> query = new HashMap<String, Object>();
				query.put("NAME", MapUtils.getString(vm, "code_nm"));
				List<Map<String, Object>> nameList = this.ibatisQueryDao.queryForList("getLevelName_select_lockkk",
						query);
				if (!nameList.isEmpty()) {
					int indexFlag = 0;
					for (Map<String, Object> v : nameList) {
						if (StringUtils.equals(MapUtils.getString(v, "code"), post.getCode())) {
							indexFlag++;
							post.setName(MapUtils.getString(vm, "code_nm") + indexFlag);
						}
					}
				} else {
					post.setName(MapUtils.getString(vm, "code_nm"));
				}
				post.setTypeId(MapUtils.getLong(vm, "sort"));// 根据code
																// 获取排位序号、typeid
				post.setSortId(null == MapUtils.getLong(vm, "sort") ? 1l : MapUtils.getLong(vm, "sort"));// 排序号
				post.setEnabled(MapUtils.getString(vm, "is_status").equals("1"));
				postList.add(post);
			}

			for (V3xOrgPost v3xOrgPost : postList) {
				organizationMessage = this.orgManagerDirect.updatePost(v3xOrgPost);
				// this.parseOrganization(organizationMessage);
			}
			rMap.put("code", "1000");
			rMap.put("result", "postAdd succ");
			log.info("==========OrgSyncManager postAdd end");
		} catch (Exception e) {
			rMap.put("code", "1001");
			rMap.put("result", "postUpdate fail");
			log.error("OrgSyncManager postUpdate error", e);
			e.printStackTrace();
		} finally {
			return StringUtils.equals("1000", rMap.get("code")) ? true : false;
		}

	}

	/**
	 * 新建岗位
	 */
	private boolean postAdd(Map<String, String> rMap) {
		log.info("==========OrgSyncManager postAdd start");
		// 获取岗位最大排序号
		List<Map<String, Object>> vl = this.ibatisQueryDao.queryForList("postAdd_select_lockkk", null);
		List<Map<String, Object>> sortL = this.ibatisQueryDao.queryForList("getPostMaxSort_select_lockkk", null);
		Map<String, Object> sortM = sortL.get(0);
		int index = MapUtils.getInteger(sortM, "num").intValue();
		try {
			List<V3xOrgPost> postList = new ArrayList<V3xOrgPost>();
			for (Map<String, Object> vm : vl) {
				index++;
				V3xOrgPost post = new V3xOrgPost();
				post.setIdIfNew();
				post.setOrgAccountId(this.accountId);
				post.setCode(MapUtils.getString(vm, "code"));
				Map<String, Object> query = new HashMap<String, Object>();
				query.put("NAME", MapUtils.getString(vm, "code_nm"));
				List<Map<String, Object>> nameList = this.ibatisQueryDao.queryForList("getPostName_select_lockkk",
						query);
				if (!nameList.isEmpty()) {
					for (Map<String, Object> v : nameList) {
						if (StringUtils.equals(MapUtils.getString(v, "name"), MapUtils.getString(vm, "code_nm"))) {
							post.setName(MapUtils.getString(vm, "code_nm") + nameList.size());
							break;
						} else {
							post.setName(MapUtils.getString(vm, "code_nm"));
						}
					}
				} else {
					post.setName(MapUtils.getString(vm, "code_nm"));
				}
				post.setTypeId(MapUtils.getLong(vm, "type"));// 岗位类别(管理类 1)
				post.setSortId((long) index);// 排序号(为1)
				organizationMessage = this.orgManagerDirect.addPost(post);
				postList.add(post);
			}
			rMap.put("code", "1000");
			rMap.put("result", "postAdd succ");
			log.info("==========OrgSyncManager postAdd end");
		} catch (Exception e) {
			rMap.put("code", "1001");
			rMap.put("result", "postAdd fail");
			log.error("OrgSyncManager postAdd error", e);
			e.printStackTrace();
		} finally {
			return StringUtils.equals("1000", rMap.get("code")) ? true : false;
		}

	}

	/**
	 * 
	 * 更新部门 void
	 * 
	 * @param rMap
	 * @throws BusinessException
	 */
	private boolean departmentUpdate(Map<String, String> rMap) throws BusinessException {
		log.info("==========OrgSyncManager departmentUpdate start");
		List<Map<String, Object>> vl = this.ibatisQueryDao.queryForList("depUpdate_select_lockkk", null);
		try {
			for (Map<String, Object> vm : vl) {
				V3xOrgDepartment dep = this.orgManager.getDepartmentById(MapUtils.getLong(vm, "id"));
				dep.setName(MapUtils.getString(vm, "name"));
				dep.setSuperior(MapUtils.getLong(vm, "supid"));
				dep.setEnabled(MapUtils.getString(vm, "is_status").equals("1"));// org_dep
																				// status=1//
																				// 表示正常//
																				// 0表示停用
				dep.setSortId(null == MapUtils.getLong(vm, "sort") ? 1l : MapUtils.getLong(vm, "sort"));// 稍后注释掉，修复实施导入时自己生成的sort
				organizationMessage = this.orgManagerDirect.updateDepartment(dep);
				// this.parseOrganization(organizationMessage);
			}

			rMap.put("code", "1000");
			rMap.put("result", "departmentUpdate succ");
			log.info("==========OrgSyncManager departmentUpdate end");
		} catch (Exception e) {
			rMap.put("code", "1001");
			rMap.put("result", "departmentUpdate fail");
			log.error("OrgSyncManager departmentUpdate error", e);
			e.printStackTrace();
		} finally {
			return StringUtils.equals("1000", rMap.get("code")) ? true : false;
		}
	}

	/**
	 * 
	 * 新建部门 void
	 * 
	 * @throws BusinessException
	 */
	private boolean departmentAdd(Map<String, String> rMap) {
		try {
			log.info("==========OrgSyncManager departmentAdd start");
			// 添加一级部门
			List<Map<String, Object>> vl2 = this.ibatisQueryDao.queryForList("deptAdd_select_lockkk", null);
			Map<String, V3xOrgDepartment> depMap = new HashMap<String, V3xOrgDepartment>();
			// 查询部门最大排序号
			List<Map<String, Object>> sortL = this.ibatisQueryDao.queryForList("getDeptMaxSort_select_lockkk", null);
			Map<String, Object> sortM = sortL.get(0);
			int index = MapUtils.getInteger(sortM, "num").intValue();
			for (Map<String, Object> vm : vl2) {
				index++;
				String code = MapUtils.getString(vm, "dept");
				String supcode = MapUtils.getString(vm, "supid");

				String name = MapUtils.getString(vm, "name");
				V3xOrgDepartment dep = new V3xOrgDepartment();
				Long supId = 0L;
				if (null != depMap.get(supcode)) {
					supId = depMap.get(supcode).getId();
				} else {
					supId = this.findDepartmentByCode(supcode);
				}
				Map<String, Object> query = new HashMap<String, Object>();
				query.put("NAME", name);
				List<Map<String, Object>> nameList = this.ibatisQueryDao.queryForList("getDeptName_select_lockkk",
						query);
				if (!nameList.isEmpty()) {
					for (Map<String, Object> v : nameList) {
						if (StringUtils.equals(MapUtils.getString(v, "name"), name)
								&& StringUtils.equals(MapUtils.getString(v, "supcode"), supcode)) {
							name += nameList.size();
							break;
						}
					}
				}
				dep.setIdIfNew();
				dep.setCode(code);
				dep.setName(name);
				dep.setOrgAccountId(this.accountId);
				dep.setSuperior(supId);
				dep.setSortId((long) index);
				organizationMessage = this.orgManagerDirect.addDepartment(dep);
				depMap.put(code, dep);
			}
			rMap.put("code", "1000");
			rMap.put("result", "departmentAdd succ");
			log.info("==========OrgSyncManager departmentAdd end");
		} catch (Exception e) {
			log.error("OrgSyncManager departmentAdd error", e);
			rMap.put("code", "1001");
			rMap.put("result", "departmentAdd fail");
			e.printStackTrace();
		} finally {
			return StringUtils.equals("1000", rMap.get("code")) ? true : false;
		}
	}

	/**
	 * 解析组织架构同步的日志,将同步错误解析,并抛出错误异常
	 * 
	 * @param organizationMessage
	 * @return
	 * @throws BusinessException
	 */
	private void parseOrganization(OrganizationMessage organizationMessage) throws BusinessException {
		if (!organizationMessage.isSuccess()) {
			List<OrgMessage> errorMsgs = organizationMessage.getErrorMsgs();
			if (!errorMsgs.isEmpty()) {
				OrgMessage orgMessage = errorMsgs.get(0);
				V3xOrgEntity entity = orgMessage.getEnt();
				String code = entity.getCode();
				String name = entity.getName();
				String errorCode = "MessageStatus." + orgMessage.getCode().toString();

				String message = "code:" + code + ",name:" + name + ",error:" + ResourceUtil.getString(errorCode);
				throw new BusinessException(message);
			}
		}
	}

	/**
	 * 根据编号查询部门
	 * 
	 * @param code
	 * @return
	 * @throws BusinessException
	 */
	private Long findDepartmentByCode(String code) throws BusinessException {
		if (StringUtils.isEmpty(code))
			return this.accountId;
		Map<String, Object> query = new HashMap<String, Object>();
		query.put("code", code);
		List<Map<String, Object>> vl = this.ibatisQueryDao.queryForList("findDepByCode_select_lockkk", query);
		if (vl.isEmpty()) {
			return this.accountId;
		}
		return MapUtils.getLong(vl.get(0), "id");
	}

	/**
	 * 地区同步
	 * 
	 * @param code
	 * @return
	 * @throws BusinessException
	 */
	private boolean addEstab(Map<String, String> rMap) {
		try {
			log.info("==========OrgSyncManager addEstab start");
			// 添加一级部门
			List<Map<String, Object>> vl = this.ibatisQueryDao.queryForList("estab_select_lockkk", null);
			for (Map<String, Object> map : vl) {
				String dataXml = this.freemarkFlowManager.fltTemplateIntoString("datasync/daka/addEstabXML.ftl", map);
				FormFactory formFactory = (FormFactory) AppContext.getBean("formFactory");
				FormExport[] formExportData = FormUtils.xmlTransformFormExports(dataXml);
				for (FormExport formExport : formExportData) {
					formFactory.importBusinessFormData("admin", "Lk_RYDQ_47", formExport, null);
				}
			}
			rMap.put("code", "1000");
			rMap.put("result", "addEstab succ");
			log.info("==========OrgSyncManager addEstab end");
		} catch (Exception e) {
			log.error("OrgSyncManager addEstab error", e);
			rMap.put("code", "1001");
			rMap.put("result", "addEstab fail");
			e.printStackTrace();
		} finally {
			return StringUtils.equals("1000", rMap.get("code")) ? true : false;
		}
	}

	public OrganizationMessage getOrganizationMessage() {
		return organizationMessage;
	}

	public void setOrganizationMessage(OrganizationMessage organizationMessage) {
		this.organizationMessage = organizationMessage;
	}

	public OrgManager getOrgManager() {
		return orgManager;
	}

	public void setOrgManager(OrgManager orgManager) {
		this.orgManager = orgManager;
	}

	public OrgManagerDirect getOrgManagerDirect() {
		return orgManagerDirect;
	}

	public void setOrgManagerDirect(OrgManagerDirect orgManagerDirect) {
		this.orgManagerDirect = orgManagerDirect;
	}

}
